package com.k2data.k2app.service;

import com.k2data.app.kmx.KmxClient;
import com.k2data.app.kmx.cond.KmxCond;
import com.k2data.app.kmx.domain.Field;
import com.k2data.k2app.common.KmxParams;
import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.domain.po.TMonitorPoint;
import com.k2data.k2app.mapper.TMonitorPointMapper;
import com.k2data.k2app.mapper.TMonitorVariableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lidong9144@163.com 17-7-13.
 */
@Service
public class KmxFieldGroupService {

    private final TMonitorPointMapper tMonitorPointMapper;
    private final KmxParams kmxParams;
    private final TMonitorVariableMapper tMonitorVariableMapper;
    @Autowired
    MyConstant myConstant;
    @Autowired
    public KmxFieldGroupService(TMonitorPointMapper tMonitorPointMapper, KmxParams kmxParams,
                                TMonitorVariableMapper tMonitorVariableMapper) {
        this.tMonitorPointMapper = tMonitorPointMapper;
        this.kmxParams = kmxParams;
        this.tMonitorVariableMapper = tMonitorVariableMapper;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addFieldGroup(TMonitorPoint point, List<Field> fields) throws InterruptedException {
        TMonitorPoint tMonitorPoint = new TMonitorPoint();
        tMonitorPoint.setId(point.getId());
        tMonitorPoint.setState(1);
        tMonitorPointMapper.updateByPrimaryKeySelective(tMonitorPoint);

        for (Field field : fields) {
            if (field.getIdField()) {
                continue;
            }
            tMonitorVariableMapper.updateState(point.getId(), field.getName(), 1);
        }

        // fieldgroup 截取
        /*String[] ids = point.getNameEn().split("_");
        String id = ids[0]+"_"+ids[1];*/
        String fieldGroupId = myConstant.getFieldGroup(point.getNameEn());
//        String[] names = point.getSensorName().split("_");
//        String name = names[0]+"_"+names[1];
        String name = point.getSensorName();
        KmxCond kmxCond = KmxCond.fieldGroups(kmxParams.getKmxInitParams())
                .post()
                .id(fieldGroupId)
                .name(name)
                .description(name)
                .fields(fields)
                .build();
        KmxClient.sync(kmxCond);
    }

}
